我有一个这样的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测试。我认为这是因为承诺还没有解决..有一种方法从承诺返回一个值?
要使用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); }
当你从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 :)
}
我更喜欢使用“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()提供)。
它可能会说你应该执行resolve(someObject);在承诺实现的内部。
然后在你的Then代码中,你可以引用someObject来做你想做的事情。
解决承诺后,你无法返回价值。而是在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();
您需要使用引用数据类型,如数组或对象。
function foo(u,n){
let result = [];
const userBrands = new Promise((res, rej)=> {
res(['brand 1', 'brand 3']);
})
userBrands.then((ub)=>{
return new Promise((res, rej) =>{
res([...ub, 'brand 4', 'brand 5']);
})
}).then(response => {
return result.push(...response);
});
return result;
};
foo();
我认为最初的海报想要的是从一个承诺返回一个未包装的值,而不实际返回另一个承诺。除非另有证明,否则恐怕这在then()或async/await上下文之外是不可能的。无论如何,你总能得到承诺。