问题描述
我有一个异步函数,可以在成功执行后提供数据。 我必须在多个地方创建异步读取调用函数,但是在其中一个函数调用中,由于对检索到的数据有依赖性,因此我希望将其与promise一起使用。 我该如何在没有承诺的情况下重用相同的函数调用,以减少冗余代码?
asyncFunc(); // returns "abcd"
doSomething(); // doesn't matter if we have the data "abcd" yet
asyncFunc().then(function (val){
doSomeOtherThing(val);
})
“ asyncFunc”未返回任何承诺。我想将其用作Promise函数。
解决方法
将诺言分配给创建时的常量。像
const promise = asyncFunc(); // returns "abcd"
doSomething(); // doesn't matter if we have the data "abcd" yet
promise.then(function (val){
doSomeOtherThing(val);
})