【发布时间】:2019-02-16 11:28:20
【问题描述】:
我有以下代码:
function someAsyncOperation(){
const myArray = [1,2,3,4,5];
return Promise.resolve(myArray);
// return Promise.reject("Reject from someAsyncOperation");
}
const random = () => {
return Math.floor(Math.random() * 10) + 1;
}
const myFunction = (item) => {
return someAsyncOperation() // this function returns an array
.then((array) => {
if(!array.includes(item)){
console.log(`The element ${item} has NOT been found inside the array`);
return myFunction(random()).then((r) => console.log(`Hello World ${r}`));
}
else{
console.log(`The element ${item} has been found inside the array`);
return item;
}
});
}
myFunction(random()).then(res => {
// success
console.log("Success", res);
}).catch(err => {
// handle error here which could be either your custom error
// or an error from someAsyncOperation()
console.log("Error", err);
});
以下是它的结果的一些示例:
第一个答案示例
The element 10 has NOT been found inside the array
The element 8 has NOT been found inside the array
The element 7 has NOT been found inside the array
The element 5 has been found inside the array
Hello World 5
Hello World undefined
Hello World undefined
Success undefined
第二个答案示例
The element 9 has NOT been found inside the array
Nuevo elemento random generado 10
The element 10 has NOT been found inside the array
Nuevo elemento random generado 3
The element 3 has been found inside the array
Hello World 3
Hello World undefined
Success undefined
第三个答案示例
The element 5 has been found inside the array
Success 5
所以,我的问题是:
为什么有时会输出Hello World undefined 和Success undefined?我的意思是:then 在return myFunction(random()).then((r) => console.log(Hello World ${r})); 中是做什么的???
编辑:
Exaclty,我希望在return r(JaromandaX 的回答如下)中不仅有找到的结果,还有历史未找到结果按它们出现的顺序排列。这是我需要的一个例子:
The element 10 has NOT been found inside the array
The element 8 has NOT been found inside the array
The element 7 has NOT been found inside the array
The element 5 has been found inside the array
Hello World 10
Hello World 8
Hello World 7
Success 5
【问题讨论】:
标签: javascript node.js asynchronous promise es6-promise