我有一个这样的javascript代码:
function justTesting() {
promise.then(function(output) {
return output + 1;
});
}
var test = justTesting();
我总是得到一个未定义的值的var测试。我认为这是因为承诺还没有解决..有一种方法从承诺返回一个值?
我有一个这样的javascript代码:
function justTesting() {
promise.then(function(output) {
return output + 1;
});
}
var test = justTesting();
我总是得到一个未定义的值的var测试。我认为这是因为承诺还没有解决..有一种方法从承诺返回一个值?
当前回答
我在这里所做的是从justTesting函数返回一个承诺。然后,在解析函数时就可以得到结果。
// 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);
});
希望这能有所帮助!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
其他回答
我更喜欢使用“await”命令和async函数来消除承诺的混淆,
在这种情况下,我会先写一个异步函数, 这将用来代替“promise”下调用的匿名函数。那么“这个问题的一部分是:
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;
}
然后从main function调用这个函数:
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
注意,这里我将主函数和子函数都返回给异步函数。
当你从then()回调返回一些东西时,这有点神奇。如果返回一个值,则使用该值调用next then()。但是,如果返回一些类似承诺的东西,则next then()将等待它,并且仅在承诺解决(成功/失败)时调用。
来源:https://web.dev/promises/ queuing-asynchronous-actions
我在这里所做的是从justTesting函数返回一个承诺。然后,在解析函数时就可以得到结果。
// 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);
});
希望这能有所帮助!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
要使用promise,必须调用创建promise的函数,或者自己创建一个promise。你没有真正描述你真正想要解决的问题,但下面是你自己如何做出承诺的方法:
函数justTesting(input) { 返回新的Promise(函数(解析,拒绝){ //一些异步操作 setTimeout(函数(){ //用一些值来解决承诺 Resolve (input + 10); }, 500); }); } justTesting(29),然后(函数(val) { //你在这里获得了承诺的价值 日志(val); }); //在代码片段中显示输出 函数log(x) { document . write (x); }
或者,如果你已经有一个返回承诺的函数,你可以使用该函数并返回它的承诺:
//返回promise的函数 函数延迟(t) { 返回新的承诺(函数(resolve) { setTimeout(函数(){ 解决(); }, t); }); } 函数justTesting(input) { 返回延迟(100).then(函数(){ 返回输入+ 10; }); } justTesting(29),然后(函数(val) { //你在这里获得了承诺的价值 日志(val); }); //在代码片段中显示输出 函数log(x) { document . write (x); }
解决承诺后,你无法返回价值。而是在promise被解析时调用另一个函数:
function justTesting() {
promise.then(function(output) {
// instead of return call another function
afterResolve(output + 1);
});
}
function afterResolve(result) {
// do something with result
}
var test = justTesting();