为什么这个简单的 JS 承诺会返回一个承诺?

编程入门 行业动态 更新时间:2024-10-14 20:21:58
本文介绍了为什么这个简单的 JS 承诺会返回一个承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一个非常简单的问题.我已经把它归结为最简单的版本来说明我的问题.

为什么这个vanilla JS会返回一个promise,我怎样才能让它返回Hello"?

让结果 = 测试().then(函数(结果){返回结果;});警报(结果);功能测试(序列化){返回新的承诺(功能(解决,拒绝){解决(你好");});}

解决方案

发生的事情是您正在警告"then 方法返回的值.

then 方法总是会返回一个 promise,即使你返回的是一个值,它也会被封装在一个已解析的 promise 中(例如 Promise.resolve('Hello')),这样你就可以实现chainability,比如你可以在then回调中调用和返回其他promise,它们会等待解析继续并解析.>

test().then(函数(结果){控制台日志(结果);返回结果+'世界!';}).那么(函数(结果2){控制台日志(结果2);//你好,世界!return new Promise(function (resolve) { resolve('End') });}).then(函数(结果){控制台日志(结果);})功能测试(序列化){返回新的承诺(功能(解决,拒绝){解决(你好");});}

A really simply question. I've boiled it down to the simplest version that illustrates my problem.

Why does this vanilla JS return a promise, and how can I get it to return "Hello"?

let result = test() .then(function(result) { return result; }); alert(result); function test(serialized) { return new Promise(function(resolve, reject) { resolve("Hello"); }); }

解决方案

What's happening is that you are "alerting" the value returned by the then method.

The then method will always return a promise, even if you are returning a value, it's wrapped in a resolved promise (e.g. Promise.resolve('Hello')), this allows you to achieve chainability, for instance you can call and return other promises in the then callback, and they will wait the resolution to continue and resolve.

test() .then(function(result) { console.log(result); return result + ' world!'; }).then(function(result2) { console.log(result2); // Hello world! return new Promise(function (resolve) { resolve('End') }); }).then(function (result) { console.log(result); }) function test(serialized) { return new Promise(function(resolve, reject) { resolve("Hello"); }); }

更多推荐

为什么这个简单的 JS 承诺会返回一个承诺?

本文发布于:2023-10-24 21:11:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!