为什么要获取回报承诺未决? [英] Why fetch returns promise pending?

查看:75
本文介绍了为什么要获取回报承诺未决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用访存来获取数据,但它会继续将promise作为待处理状态返回.我已经看过很多有关此问题的帖子,并尝试了所有可能的方法,但没有解决我的问题.我想知道为什么提取操作简单地将诺言返回为待处理状态?

I am using fetch to get data but it keeps returning promise as pending. I've seen many posts regarding this issue and tried all the possibilities but didn't solve my issue. I wanted to know why the fetch returns promise as pending in brief what are the possible cases where fetch returns pending status?

我的代码片段:

fetch(res.url).then(function(u){ 
    return u.json();
})
.then(function(j) { 
    console.log(j); 
});

推荐答案

Promises are a way to allow callers do other work while waiting for result of the function.

请参见承诺使用承诺:

一个承诺处于以下状态之一:

A Promise is in one of these states:

  • 待定:初始状态,既未实现也不被拒绝.
  • 已完成:表示该操作已成功完成.
  • 已拒绝:表示操作失败.
  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

fetch(url)返回Promise对象.它允许使用可以响应结果值(响应请求)的.then(…)附加侦听器". .then(…)再次返回Promise对象,该对象将给出结果.

The fetch(url) returns a Promise object. It allows attaching "listener" to it using .then(…) that can respond to result value (response to the request). The .then(…) returns again Promise object that will give result forward.

您可以使用JS语法糖来使用Promises:

You can use JS syntax sugar for using Promises:

async function my_async_fn(url) {
    let response = await fetch(url);
    console.log(response); // Logs the response
    return response;
)

console.log(my_async_fn(url)); // Returns Promise

async function返回一个Promise. await关键字将其他功能包装在.then(…)中.这等效于没有awaitasync的情况:

async functions return a Promise. await keyword wraps rest of the function in .then(…). Here is equivalent without await and async:

// This function also returns Promise
function my_async_fn(url) {
    return fetch(url).then(response => {
        console.log(response); // Logs the response
        return response;
    });
)

console.log(my_async_fn(url)); // Returns Promise

再次参见MDN上的有关承诺的文章

这篇关于为什么要获取回报承诺未决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆