我正在嘗試reduce使用異步和同步方法的陣列。我有兩種同步方法和一種異步方法,可以對物件進行一些基本的格式化。因為我有異步和同步的搭配方法,我用async/await我的reduce。問題是我的formatName方法回傳錯誤,Cannot read property 'toUpperCase' of undefined因為person傳入的引數是一個承諾。我認為因為我await在我的reduce中使用,回呼應該回傳實際值而不是一個promise:
const results = await fn(finalResult);
如果我從陣列中取出同步方法,我的代碼就可以正常作業。但我需要減少同步和異步方法的陣列。有沒有人有關于我如何解決這個問題的提示?我的完整代碼如下。
const formatName = (person) => {
person.name = person.name.toUpperCase();
return person;
}
const formatAge = (person) => {
person.age = 10;
return person;
}
// Async function
const formatLocation = async (person) => {
await new Promise(resolve => setTimeout(resolve, 1000));
person.location = `${person.location.toLocaleLowerCase()}`
return person;
}
const initialPerson = {
name: "john",
age: 35,
location: 'USA'
}
const formattedStagesWithAsync = [
formatLocation, // asynchronous
formatAge, // synchronous
formatName //synchronous
];
const process = async () => {
const formattedPerson = await formattedStagesWithAsync.reduce(async (finalResult, fn) => {
const results = await fn(finalResult);
return results;
}, initialPerson);
console.log(`Formatted person - ${JSON.stringify(formattedPerson, null, 2)}`);
}
process();
uj5u.com熱心網友回復:
異步函式總是回傳承諾,因此在.reduce回呼的后續迭代中,累加器將是您需要先解決的承諾。
雖然你可以做
const accumVal = await finalResult
在回呼開始時,通過reduce完全避免IMO ,這會簡單得多。
const process = async () => {
let person = initialPerson;
for (const fn of formattedStagesWithAsync) {
person = await fn(person);
}
如果您的每個函式都回傳原始物件,就像這里的情況一樣,則簡化為:
const process = async () => {
for (const fn of formattedStagesWithAsync) {
await fn(initialPerson);
}
(你也在initialPerson你的原始代碼中改變了)
uj5u.com熱心網友回復:
Promise回傳async值但不使用async和await選項 for Promise,就return這樣
承諾檔案
const promiseHandler = () => {
return new Promise((done, reject) => {
setTimeout(() => {
done("hello");
});
});
}
promiseHandler().then(v => {
console.log(v); // hello
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/351231.html
標籤:javascript ecmascript-6 异步等待 降低
