Good programmers how to use the web front-end tutorial Share promise to solve the callback and asynchronous

Good programmers how to use the web front-end tutorial Share promise to solve the callback and asynchronous
First, let us look at the following questions What is the output?

setTimeout(function() {
      console.log(1);
},1000)
console.log(2);

Our results are: first output 2, output 1; this is what causes it? We should all know the timer is asynchronous; it is the first to output 2;
then our demand, and how to output 1, 2 and then output it?

function foo(callback) {
setTimeout(function() {
    console.log(1);
    callback();
},1000)
}
foo(function() {
      console.log(2);
})

Now we look at the results print it, and sure enough the first output of 1, then the output 2; this is solved by callback;
now I'm what you need changed, we do once every 1 second output;

function foo(callback) {
    setTimeout(function() {
        console.log('1秒后输出');
        callback()
    }, 1000)
}
foo(function() {
    console.log('第一次输出');
    foo(function() {
        console.log('第二次输出');
        foo(function() {
            console.log('第二次输出');
        })
    })
})

This is not a solution to our problem of it?

Yes, but if we are more than a few times, you will not find the callback too much? This is everyone talking about destroyed hell;

Therefore ES6 ### provides us a solution to destroy hell: Promise;
Promise is a method for processing asynchronous manner value, Promise is an object to solve the problem of a nested
#### promise object status:

Ongoing: pending
success: resovled
failure: rejected

promise object:

then execute () after successful; if there are two parameters: a first parameter is successfully executed, executed after the failure of the second parameter;
performed after the catch () fails;
. al promise all ([]) then ( ) after successfully the first method then executes a;
promise.race [(P1, P2, P3, ---)] as long as there is a lead in changing state, promise executes corresponding status

var promise = new Promise(function (resolved, rejected) {
resolved('ok'); 
rejected('no');
//如果成功和失败同时写,执行先写的;(特点状态一旦改变,就不可逆了)
});
promise.then(function(msg) {
console.log('ok:' + msg);
},function (msg) {
console.log('no:' + msg);
});

Print result: ok: ok
now we do an exercise: Using promise load a picture; the picture will be loaded successfully loaded into the body, if the load failed, suggesting that failure;

var promise = new Promise(function (resolved, rejected) {
var img = document.createElement('img');
img.src = './img/1.png';
img.onload = function () {
resolved(img)   //如果加载成功就返回resolved()
}
img.onerror = function () {
rejected('失败')    //如果加载成功就返回rejected()
}
})
promise.then(function (msg) {
document.body.appendChild(msg)
},function (msg) {
alert(msg)
})

How about you is not got to know of the promise?
So how to solve problems with asynchronous promise it? We do a 1 sec intervals output;
`` `function Fn () {
var = new new Promise Promise (function (resolved, Rejected) {
the setTimeout (function () {
the console.log ( 'every second');
resolved ()
}, 1000)
});
return Promise;
}
Fn () the then (function () {.
the console.log ( 'first output');
return Fn ()
.}) the then (function () {
Console .log ( 'second outputs');
return Fn ()
}) the then (function () {.
the console.log ( 'third output');
})

那Promise如何解决ajax回调的问题呢?咱们继续往下看.

ajaxPromise function (URL) {
var = new new Promise Promise (function (resolved, Rejected) {
var = new new XHR the XMLHttpRequest ();
xhr.open ( 'GET', URL);
xhr.send ();
xhr.onreadystatechange = function ( ) {
IF (xhr.readyState === === 200 is xhr.status &&. 4) {
resolved (xhr.responseText); // tell promise success
}
}
the setTimeout (function () {// after the request is less than 5 seconds
rejected ( 'error') // tell promise failed
}, 5000)
})
return promise;
}
the document.onclick = function () {
var = ajaxPromise Pro ( 'the data.json');
pro.then (function (MSG) {
Alert (MSG) // If paths, we obtain the data
}, function (MSG) {
Alert (MSG) // If we pop wrong path error
})
}

Guess you like

Origin blog.51cto.com/14573321/2456780