; .
, JavaScript, , , -, - . JavaScript , .
alert("cannot do anything until you click ok");
. , - , .
Promise.resolve(22)
.then(x=>alert("blocking")||"Hello World")
.then(
x=>console.log(
"does not resolve untill you click ok on the alert:",
x
)
);
, , , .
, -, . , JavaScript ( - fork node, , async api's).
, http-, fetch
, , ( - ). fetch .
, / node , , , , promises, , , , api .
promises (, XmlHttpRequest), promises, .
- , then
( , , ), 2 .
- : , , ( ). ( HTTP- ).
- : , , ( ). , ( , - ).
.
api ( nodejs api's) :
traditionalApi(
arg
,function callback(err,value){
err ? handleFail(err) : processValue(value);
}
);
( ). - ( ).
api promises new Promise
const apiAsPromise = arg =>
new Promise(
(resolve,reject)=>
traditionalApi(
arg,
(err,val) => (err) ? reject(err) : resolve(val)
)
)
async
, promises. . , , , . , , ?:
const handleSearch = search =>
compose([
showLoading,
makeSearchRequest,
processRespose,
hideLoading
])(search)
.then(
undefined,
compose([
showError,
hideLoading
])
);
Anayway; . , , async await
, async
, await
. someFn().then(result=>...,error=>...)
:
async someMethod = () =>
try{
const result = await someFn();
...
}catch(error){
...
}
}
try catch
, , :
var alwaysReject = async () => { throw "Always returns rejected promise"; };
alwaysReject()
.then(
x=>console.log("never happens, doesn't resolve")
,err=>console.warn("got rejected:",err)
);
await
, , async ( ). .
, , promises, , , .
Promise.all
, promises , , - . promises :
const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
urls.map(
url =>
fetch(url)
.then(
undefined,
err=>new Fail([url,err])
)
)
)
.then(
responses => {
console.log("failed requests:");
console.log(
responses.filter(
isFail
)
);
console.log("resolved requests:");
console.log(
responses.filter(
response=>!isFail(response)
)
);
}
);