返回函数并使用Promise.all调用 [英] Returning function and invoking with Promise.all

查看:117
本文介绍了返回函数并使用Promise.all调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class =snippet-code-js lang-js prettyprint-override> function getMyFunction(data){return()=> new Promise((resolve,reject)=> {resolve('here is the value:',data);});} const myFunction = getMyFunction('a'); Promise.all([myFunction,])。then ((result)=> {console.log('result:',result);});



我期待结果:这里是值:a 但我得到结果:[[功能] ]

解决方案

getMyFunction 返回一个返回承诺的 function ,因此您需要调用 myFunction 来获取承诺:



< pre class =lang-js prettyprint-override> const myFunction = getMyFunction('a');
Promise.all([
myFunction(),//< - 注意这里
])。然后((结果)=> {
console.log('结果:',结果);
});


function getMyFunction(data) {
    return () => new Promise((resolve, reject) => {
        resolve('here is the value:', data);
    });
}

const myFunction = getMyFunction('a');
Promise.all([
    myFunction,
]).then((result) => {
    console.log('result: ', result);
});

I am expecting result: here is the value: a but I instead get result: [ [Function] ].

解决方案

getMyFunction returns a function that returns a promise, so you need to call myFunction to get the promise:

const myFunction = getMyFunction('a');
Promise.all([
    myFunction(), // <-- note here
]).then((result) => {
    console.log('result: ', result);
});

这篇关于返回函数并使用Promise.all调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆