Pri*_*scy 92 javascript promise
我有一个像这样的JavaScript代码:
function justTesting() {
promise.then(function(output) {
return output + 1;
});
}
var test = justTesting();
Run Code Online (Sandbox Code Playgroud)
对于var测试,我总是有一个未定义的值.我认为这是因为承诺没有解决喷射......有没有办法从承诺中返回一个价值?
c0m*_*ing 117
当你从then()回调中返回一些东西时,它有点神奇.如果返回一个值,则使用该值调用next then().但是,如果你返回类似promise的东西,那么next()会等待它,并且仅在该promise承诺(成功/失败)时被调用.
jfr*_*d00 48
要使用承诺,您必须调用创建承诺的函数或者您必须自己创建承诺.你并没有真正描述你真正试图解决的问题,但是你要自己创建一个承诺:
function justTesting(input) {
return new Promise(function(resolve, reject) {
// some async operation here
setTimeout(function() {
// resolve the promise with some value
resolve(input + 10);
}, 500);
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}Run Code Online (Sandbox Code Playgroud)
或者,如果您已经有一个返回promise的函数,则可以使用该函数并返回其promise:
// function that returns a promise
function delay(t) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, t);
});
}
function justTesting(input) {
return delay(100).then(function() {
return input + 10;
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}Run Code Online (Sandbox Code Playgroud)
小智 9
我更喜欢使用“await”命令和异步函数来摆脱承诺的混乱,
In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :
async function SubFunction(output){
// Call to database , returns a promise, like an Ajax call etc :
const response = await axios.get( GetApiHost() + '/api/some_endpoint')
// Return :
return response;
}
Run Code Online (Sandbox Code Playgroud)
and then I would call this function from main function :
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
Run Code Online (Sandbox Code Playgroud)
Noting that I returned both main function and sub function to async functions here.
我在这里做的是我从justTesting函数返回了一个promise.然后,您可以在解析函数时获得结果.
// new answer
function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}
justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
我认为原始海报想要的是从承诺中返回未包装的值,而不实际返回另一个承诺。除非另有证明,否则恐怕这在 athen()或 async/await 上下文之外是不可能的。无论如何,你总会得到一个承诺。
Promises不“返回”值,它们将它们传递给回调(您使用 .then() 提供)。
它可能试图说你应该resolve(someObject);在承诺实现中做。
然后在您的then代码中您可以参考someObject做您想做的事情。
| 归档时间: |
|
| 查看次数: |
116757 次 |
| 最近记录: |