如何管理对异步服务的可变调用计数



给定:

[1,2,3,4,5] variable array of numbers

我想为数组中的每个数字调用一个异步方法。有什么方法可以解决这个问题?异步方法的返回类型是JSON。

我所期待的是一个新的JSON数组,其中包含调用的结果

[{id:1,name:"name1"},
{id:2,name:"name2"},
{id:3,name:"name3"},
{id:4,name:"name4"},
{id:5,name:"name5"}]

最新结果

app.js

( () => {
const result =  adapterContext.get([1, 2, 3]);
console.log(result);
})();

service.js

exports.get = list => {
Promise.all(list.map(promise-method-call))
.then(function (response) {
console.log("response", response);
return response;
}).catch(function (error) {
console.log("oops ", error);
});
};

结果

为什么console.log(结果(未定义?

undefined  
response [ '{"hello":1}', '{"hello":2}', '{"hello":3}' ]  

您就快到了。首先,您需要从您的服务返回Promise.all呼叫:

exports.get = list => {
// Make sure to return the promise!
return Promise.all(list.map(promise-method-call))
.then(function (response) {
console.log("response", response);
return response;
}).catch(function (error) {
console.log("oops ", error);
});
};

然后,在应用程序内部需要等待get方法完成。有两种方法可以做到这一点:

老派.then链接:

(() => {
const result =  adapterContext.get([1, 2, 3]).then(result => {
console.log(result);
});
})();

酷孩子异步/等待

(async () => {
const result = await adapterContext.get([1, 2, 3]);
console.log(result);
})();

我想您正在寻找Promise.all。在不知道方法或api的细节的情况下,我不能确定,但您可能想要const results = await Promise.all(array.map(someMethod))之类的东西。

好吧,这里有一些可以帮助你的东西,运行这个片段,看看结果是什么。

var getAsyncObjectWithList = function(idList) {
const promiseHandler = function(resolve, reject) {
// fake async call, like http call
setTimeout(function() {
// fake conditional statement
// for error cases
if (!idList) { 
reject("no ids specified");
return;
}
// do actual processing here
var newList = idList.map(function(id) {
return { id: id, name: "name: "+id }
});
// return result by resolving list
resolve(newList);
},  3000)
}
return new Promise(promiseHandler);
}
// success case
getAsyncObjectWithList([1,2,3,4]).then(function(response) {
console.log("response", response);
}).catch(function(error){
console.log("oops ", error);
});
// error case
getAsyncObjectWithList().catch(function(error){
console.log("oops ", error);
});
var getAsyncObjectWithId = function(id) {
const promiseHandler = function(resolve, reject) {
// fake async call, like http call
setTimeout(function() {
// fake conditional statement
// for error cases
if (!id) {
reject("no id specified");
return;
}
// do actual processing here
var newObj = { id: id, name: "name: "+id };
// return result by resolving object
resolve(newObj);
}, 3000);
}
return new Promise(promiseHandler);
}
// success case
Promise.all([1,2,4,5].map(getAsyncObjectWithId))
.then(function(response) {
console.log("response", response);
}).catch(function(error){
console.log("oops ", error);
});
// error case
getAsyncObjectWithId().catch(function(error){
console.log("oops ", error);
});

最新更新