JS - intro to promise

- [Instructor] Callbacks are really handy for basic cases where we want to execute additional code after an asynchronous function completes. And as you might imagine, it's even possible to string callbacks together, pretty much as far as we need to. However, when we start working with code that uses multiple chained callbacks, it can be hard to write code that's both well organized and easy for humans to read. To solve this problem, modern JavaScript supports promises, which allow us to string together multiple callbacks while maintaining well organized and human readable code. A promise is an object that represents the eventual result of an asynchronous operationA promise contains information about the operation and tracks its status. It has a state property, which can be pending, fulfilled, or rejected, and it has a result property which starts as undefined, and can be given a value based on the operation.When the operation is complete, the promise executes one of two methods, resolve, meaning that the operation was successful, or reject, meaning that an error occurred

These methods change the state and result properties to reflect the outcome of the operation. You create a promise using the promise constructor. You can put code within a promise to do most anything you want, but a promise is most useful with an asynchronous task, using the resolve or reject callbacks. When a promise resolves, the result is returned. When a promise rejects, the error is returned. What makes promises easier for humans to read and understand than nested callbacks is the syntax used to work with the result of a promise. The promise specification allows additional methods to be chained to the code that calls the original promise, in order to work with the result of the promise. To work with the result of a resolved promise, you can add the then method. Note that there are a few common ways you might see the promise then code organized, because JavaScript ignores white space, it's fine to use any combination of line breaks and indents that works for you. Whatever format you choose, you have the possibility of stringing together a number of then methods, all indented the same amount, and with a clear flow from one to the next, making the progression of code visually obvious to you and other developers.

function get(url) {
  return new Promise(function(resolve, reject) {
    let httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', url);
    httpRequest.onload = function() {
      if (httpRequest.status === 200) {
        // Resolve the promise with the response text
        // success(httpRequest.responseText);
        resolve(httpRequest.response);
      } else {
        // Reject the promise with the status text
        // fail(httpRequest.status);
        reject(Error(httpRequest.statusText));
      }
    };

    // Handle network errors
    httpRequest.onerror = function() {
      reject(Error('Network Error'));
    };

    httpRequest.send();
  });
}

function successHandler(data) {
  const dataObj = JSON.parse(data);
  // dataObj.weather[0].icon;
}

function failHandler(status) {
  console.log(status);
}


document.addEventListener('DOMContentLoaded', function() {
  //const apiKey = '';

  const url =
    'https://api.openweathermap.org/data/2.5/weather?q=los+angeles&APPID=' +
    apiKey;
  // get(url, successHandler, failHandler);
  // console.log(get(url));
  get(url)
    .then(function(response) {
      successHandler(response);
    })
    .catch(function(status) {
      failHandler(status);
    });
});

Modern JavaScript includes a method called Fetch, that creates an asynchronous HTTP request, using a syntax that's based on promises. However, to get practice building promises from the ground up, we're going to create our own method using the Promises constructor to create and send an XHR request for the weather information on the Explore California site.So, were going to start by basically rewriting the get method that we've already created. So, our get method is just creating an XHR request, sending that, and then working with the response. And we just want to turn this into code that is actually creating, and then working with a promise. So, the first thing I'm going to do is take out the success and fail callback parameters, because promises don't actually work with those. We don't use callbacks with promises, we do have more under the hood. And then the first line of my function, I want to return a new promise. And this is a capital P using the Promise constructor. And then within the parens, I'm going to pass in an anonymous function, and that's going to have two parameters, resolve and reject, which correspond to methods inherited from the constructor.So promises are essentially callbacks under the hood, but they let us write the syntax, of course, in a way that's easier for us to work with. And so then I basically need to stick all ofthis other content, that used to be part of my get function, and just nest that inside of my new Promise. And then, I need to deal with what happens in response to the load event. So, when the status is 200, instead of calling that success callback, like I used to do, I instead want to call the resolve callback that I specified for my promise. And then for the fail case, instead of calling the fail callback, now I have a reject callback and here I can actually create an Error object, which is just adding an extra layer to my Javascript, so that I can actually generate an error in a browser console. That's not a promise specific thing. But it is something else we can do to make our errors a little bit more useful to us as developers. And then, scrolling down, to the very bottom, where I'm actually calling my get method, I'm not going to be calling it and passing in any methods right now. I'm going to comment out that previous function call, and because we don't have any response handling set up yet, I'm going to start by just console.log-ing the response. So we can see what happens when a promise resolves or rejects. So I'm just going to call that get method, pass in our URL, and consol.log the results.And so over in my browser, I have my page loading with live reload, and so here is the resultof my console.log. So my get function that returns a promise, and we can actually look inside that promise and see it has a status and a value, the status is resolved, meaning that it got a successful response, and got some data back. And then the promise value is actually that data, and when I hover over that I can actually see I have this big blob of JSON containing weather data, just like I expect. So this is the first stage of actually creating a promise.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值