首页 > 解决方案 > 如何将回调函数变成 Promise

问题描述

我需要让这段代码返回一个承诺。Idk 如何做到这一点,我想学习。如果可以的话,我还需要一些解释,谢谢!

var url = "....";

function showMoviesList(callbackFunction){
  fetch(url + "/movies", {
    method: "GET",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
  }).then(function(response){
    return response.json();
  }).then(function(moviesArray){
    callbackFunction(moviesArray);
  });
}

标签: javascriptcallbackflush-promises

解决方案


这将是

var url = "....";
function showMoviesList(callbackFunction){
  return fetch(url + "/movies", {
    method: "GET",
    headers: {
       "Content-Type": "application/x-www-form-urlencoded"
  }
  }).then(function(response){
    return response.json();
  });
}

推荐阅读