如何等待包含promise的函数



如果我们有这个函数

const getData = () => {
foo()
.then(result => {
return result;
})
.catch(error => {
return error;
});
};

虽然getData本身不是promise,但它包含了一个promise,它是异步的。

那么,等待getData返回内容的最佳方式是什么呢。Async / Await不起作用,因为它们与承诺一起工作。

谢谢。

当前,getData()不返回任何内容。你需要让它返回一个Promise,这样你就可以await或将.then()链接到它

const getData = () => {
return foo() // <-- here
.then(result => {
return result;
})
.catch(error => {
throw error;
});
};
// Now you can do :
getData().then(...)
// or :
const data = await getData();

在这种情况下,您还可以省略大括号和显式return,并使其隐式:

const getData = () => foo()
.then(result => {
return result;
})
.catch(error => {
throw error;
});

嘿,那是什么?

.then(result => {
return result;
})

这毫无作用。它获取一个值,然后不做任何操作就简单地返回它。你可以删除它。

您现在可以这样重写getData((:

const getData = async () => {
try {
return await foo()
} catch (error) {
throw error;
}
}

就这一点而言:

.catch(error => { throw error; });

或者这个:

catch (error) { throw error; }

也很没用,他们只是";继电器";(冒泡(必须在调用函数中捕获的错误。

现在很明显,getData只做了一件事,那就是返回foo(),这是一个Promise。这只是一个承诺的包装。。。所以它实际上是非常无用的。

总之,detData()根本没用。foo是一个承诺;编写一个返回Promise的函数,以便像使用Promise一样使用它只是。。。a多走一步的承诺。直接使用foo即可。

let result;
try {
result = await foo();
} catch (error) {
console.log(error);
}
console.log(result);

这将不起作用,因为getData没有返回值。您可以在foo调用之前添加一个return语句,然后等待返回值。

const getData = () => {
return foo();
};
getData().then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
要等待操作,必须返回Promise或使用回调。下面的代码片段将运行,并且应该说明它是如何工作的。我实现了一个示例foo函数,它实际上是异步的(在返回数据"12345"之前等待1秒(。我使用了async/await来说明它是如何工作的,但您同样可以返回foo的结果,而使用then

const foo = () => {
return new Promise(resolve => {
setTimeout(() => resolve('12345'), 1000);
});
}
const getData = async () => {
const data = await foo();
console.log(`Data is ${data}`);
return data;
};
getData()
.then(() => console.log('complete'))
.catch(err => console.log(`oops: ${err}`));

console.log('this prints first since async operation is still pending');

最新更新