2017-04-10 2 views
0

Hallo Ich versuche, die ID-Variable zu erhalten, die es innerhalb Anfrage in einem asynchronen Prozess mit Anforderung und cheerio zurückgegeben wird.Erhalten Variable außerhalb Modulanforderung, wenn asynchron

Ich habe versucht, indem Sie ein Versprechen zurück, aber das hat nicht funktioniert.

let id; 
 

 
    request(mainUrl, function(err, res, body) { 
 
       
 
     let $ = cheerio.load(body) 
 

 
     var links= $(".book").map(function(){ 
 
      \t \t \t return $(this).attr("href"); 
 
     \t }).get() 
 

 
    \t \t \t \t \t \t \t 
 
     var url= links[0] 
 

 

 
     var getId= url.match(/book\/show\/(\d+)/) 
 

 

 
     id= getId[1] 
 
     //This is the id I'm getting: "36474" 
 
    \t \t \t \t \t \t \t 
 
     return Promise.resolve(id) 
 

 
    }); 
 

 

 
    .then((value)=>{ 
 
    \t console.log(id) 
 

 
    })

+0

welche Anfrage lib verwenden Sie? sieht so aus, als ob Sie einen Callback-basierten verwenden, unterstützt möglicherweise nicht '.then ' –

+0

*" hat nicht funktioniert "* ist keine richtige technische Problemdiagnose – charlietfl

Antwort

0

Ok, habe ich es:

let id; 
 

 
let promise= new Promise((resolve, reject)=>{ 
 
\t \t \t request(mainUrl, function(err, res, body) { 
 
      
 
     let $ = cheerio.load(body) 
 

 
     var links= $(".book").map(function(){ 
 
     \t \t return $(this).attr("href"); 
 
    \t \t }).get() 
 

 
\t \t \t \t \t \t \t 
 
     var url= links[0] 
 

 

 
     var getId= url.match(/book\/show\/(\d+)/) 
 

 

 
     id= getId[1] 
 
     //Ex: => "36474" 
 
\t \t \t \t \t \t \t 
 

 
     return resolve(id) 
 

 
}); 
 
}) 
 

 

 
promise 
 
.then((value)=>{ 
 
\t console.log(id) 
 

 
})

Verwandte Themen